package com.xingchi.tornado.core.utils;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class IPUtils {

    public static final String UNKNOWN = "unknown";
    public static final List<String> IP_HEADER_NAMES = Lists.newArrayList(
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "REMOTE_ADDR");

    public static String getIp(HttpServletRequest request) {

        String ipAddress = UNKNOWN;
        for (String ipHeaderName : IP_HEADER_NAMES) {
            if (StringUtils.isBlank(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader(ipHeaderName);
                if (StringUtils.isNotBlank(ipAddress) && !UNKNOWN.equalsIgnoreCase(ipAddress)) {
                    break;
                }
            }
        }

        if (StringUtils.isBlank(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }

        if ("0:0:0:0:0:0:0:1".equals(ipAddress)) {
            ipAddress = "127.0.0.1";
        }

        return ipAddress;
    }

    public static String getIp(jakarta.servlet.http.HttpServletRequest request) {

        String ipAddress = UNKNOWN;
        for (String ipHeaderName : IP_HEADER_NAMES) {
            if (StringUtils.isBlank(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader(ipHeaderName);
                if (StringUtils.isNotBlank(ipAddress) && !UNKNOWN.equalsIgnoreCase(ipAddress)) {
                    break;
                }
            }
        }

        if (StringUtils.isBlank(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }

        if ("0:0:0:0:0:0:0:1".equals(ipAddress)) {
            ipAddress = "127.0.0.1";
        }

        return ipAddress;
    }
}
